package com.mgq.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @author MaGuangQi
 * 测试semaphore 对访问共享资源的线程个数进行限制(限流)
 * @date 2021-12-23 14:21
 **/
@Slf4j
public class TestSemaphore {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    log.debug("运行开始");
                    Thread.sleep(1000);
                    log.debug("运行结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }

            }).start();
        }
    }
}
